/**
 * 
 */
package hottargui.config;

import hottargui.framework.Game;
import hottargui.framework.GameData;
import hottargui.framework.Player;
import hottargui.framework.PlayerColor;
import hottargui.framework.WinnerStrategy;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class RevenueWinnerStrategy implements WinnerStrategy {

	/**
	 * 
	 * Helper class to hold color and revenue, so a collection.sort can be done
	 * using comparable interface
	 * 
	 */
	private class PlayerRevenue implements Comparable<PlayerRevenue> {
		PlayerColor color;
		int revenue;

		PlayerRevenue(PlayerColor color, int revenue) {
			this.color = color;
			this.revenue = revenue;
		}

		PlayerColor getColor() {
			return color;
		}

		int getRevenue() {
			return revenue;
		}

		/* Descending order... */
		public int compareTo(PlayerRevenue p) {
			return p.getRevenue() - getRevenue();
		}
	}

	public PlayerColor getWinner(Game game) {

		GameData gd = game.getGameObjectServer().getGameData();

		List<PlayerRevenue> revenueRanking = new ArrayList<PlayerRevenue>();

		/* Get final revenue and decide if anyone is winner */
		for (Player player : gd.getPlayers().values()) {
			revenueRanking.add(new PlayerRevenue(player.getColor(), gd.getRevenue(player)));
		}

		Collections.sort(revenueRanking);

		/*
		 * if the 2 players with most revenue collected after last round is
		 * identical then it is considered a draw
		 */
		if (revenueRanking.get(0).getRevenue() != revenueRanking.get(1).getRevenue()) {
			return revenueRanking.get(0).getColor();
		}
		return PlayerColor.None;
	}
}
